<template>
  <d2-container>
  <div class="app-container">
    <el-container>
      <el-main class="theme-front-color">

        <el-tabs v-model="tabActive" type="card" @tab-click="tabClick">
          <el-tab-pane label="采集器" name="1">
            <el-table
              :data="collectTableDataList"
              border
              v-loading="dataListLoading"
              style="width: 100%;overflow:auto;"
            >
              <el-table-column
                prop="equiCode"
                header-align="center"
                align="center"
                label="采集设备编码">
              </el-table-column>
              <el-table-column
                prop="equiName"
                header-align="center"
                align="center"
                label="采集设备名称">
              </el-table-column>
              <el-table-column
                prop="equiIp"
                header-align="center"
                align="center" min-width="90"
                label="IP">
              </el-table-column>
              <el-table-column
                prop="equiPort"
                header-align="center"
                align="center"
                label="端口">
              </el-table-column>
              <el-table-column
                prop="equiAddress"
                header-align="center"
                align="center"
                label="采集设备安装地址">
              </el-table-column>
              <el-table-column
                prop="sn"
                header-align="center"
                align="center"
                label="设备序列号">
              </el-table-column>
              <el-table-column
                prop="equiLastupdate"
                header-align="center"
                align="center" min-width="110"
                label="采集设备更新时间">
              </el-table-column>
              <el-table-column
                prop="buildId"
                header-align="center"
                min-width="center"
                label="区域编号">
              </el-table-column>
              <el-table-column
                prop="gatewayId"
                header-align="center"
                align="center"
                label="网关号">
              </el-table-column>
              <el-table-column
                prop="status"
                header-align="center"
                align="center"
                min-width="80"
                label="设备状态">
                <template slot-scope="scope">
                    <span style='color: red' v-if="(new Date().getTime() - new Date(scope.row.equiLastupdate).getTime()) >  scope.row.heartbeat * 1000 * 3 ">掉线</span>
                    <span style='color: green' v-else> 正常</span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="mt-4"
              @size-change="sizeCollectChangeHandle"
              @current-change="currentCollectChangeHandle"
              :current-page="collectPage.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="collectPage.size"
              :total="collectPage.total"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </el-tab-pane>
          <el-tab-pane label="计量器" name="2">
             <div class="search">
                <el-form label-position="right" :model="dataForm" :inline="true">
                    <el-form-item class="el-form-item--mini" label="分类" label-width="40px">
                      <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini">
                        <el-option
                          v-for="(item, index) in meterTypeList" :key="index"
                          :label="item.paramValue"
                          :value="item.paramKey">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item class="el-form-item--mini" label="计量器名称" label-width="100px">
                      <el-input v-model="dataForm.meterName" size="mini" placeholder="计量器名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item class="el-form-item--mini" label="" label-width="100px">
                        <el-checkbox v-model="dataForm.status" label="0">离线</el-checkbox>
                    </el-form-item>

                    <el-form-item class="el-form-item--mini">
                      <el-button
                        class="filter-item"
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="tabClick"
                      >查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
             <el-table
                :data="meterTableDataList"
                border
                v-loading="dataListLoading"
                style="width: 100%;overflow:auto;"
              >
              <el-table-column
                prop="meterCode"
                header-align="center"
                align="center"
                label="计量器编号">
              </el-table-column>
               <el-table-column
                 prop="meterName"
                 header-align="center"
                 align="center"
                 label="计量器名称">
               </el-table-column>
              <el-table-column
                prop="meterAddr"
                header-align="center"
                align="center"
                label="计量器物理地址">
              </el-table-column>
              <!-- <el-table-column
                prop="meterModel"
                header-align="center"
                align="center"
                label="计量器型号">
              </el-table-column> -->
              <el-table-column
                prop="meterType"
                header-align="center"
                align="center"
                min-width="60"
                label="计量器类型">
                <template slot-scope="scope">
                  {{scope.row.meterType |meterTypeName(meterTypeList)}}
                </template>
              </el-table-column>
              <!-- <el-table-column
                prop="meterSetupaddr"
                header-align="center"
                align="center"
                label="计量器安装位置">
              </el-table-column>
              <el-table-column
                prop="sn"
                header-align="center"
                align="center"
                label="计量器序列号">
              </el-table-column> -->
              <el-table-column
                prop="meterLastupdate"
                header-align="center"
                align="center" min-width="110"
                label="最新上报数据时间">
              </el-table-column>
              <el-table-column
                prop="meterStatus"
                header-align="center"
                align="center"
                min-width="80"
                label="计量器状态">
                <template slot-scope="scope">
                  <span style='color: red' v-if="(new Date().getTime() - new Date(scope.row.meterLastupdate).getTime()) >  scope.row.uploadcycle * 1000 * 3 ">掉线</span>
                  <span style='color: green' v-else> 正常</span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="mt-4"
              @size-change="sizeMeterChangeHandle"
              @current-change="currentMeterChangeHandle"
              :current-page="meterPage.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="meterPage.size"
              :total="meterPage.total"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </el-tab-pane>
        </el-tabs>

      </el-main>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import Config from "@/utils/config"
import Minix from '../power/mixin'
export default {
  name: "device",
  mixins:[Minix],

  data() {
    return {
      meterAlarmRange:20*60*1000,
      collectAlarmRange:10,
      statusList:[{'label':'异常',"value":'0'},{'label':'正常',"value":'1'}],
      meterTypeList:[],
      collectDataList: [],

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      Config:Config,
      dataForm: {
        date:'',
        dateType:'datetimerange',
        energyType:'',
        meterName:'',
        status:'',
      },
      collectPage: {
        page: 1,
        total: 0,
        size: 20
      },
      collectTableDataList:[],
      meterPage: {
        page: 1,
        total: 0,
        size: 20
      },
      meterTableDataList:[],
      dataListLoading:false,
      unit:'',
      tabActive:'1',
      timeOut:null,
    };
  },
  created() {
    this.queryStatic("METER_TYPE",null,data=>{
      if (data && data.code === 0) {
        this.meterTypeList = data.page
        this.dataForm.energyType = data.page[0].paramKey;
        this.unit =this.meterTypeList.find(item=>this.dataForm.energyType==item.paramKey).paramExt;
      } else {
        this.meterTypeList = []
      }
    });
    this.getCollectDataList();
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    tableHeight(){
      return Util.getClientHeight() - 340;
    }
  },
  methods: {
    tabClick(){
      //采集器
      if(this.tabActive==1){
        this.getCollectDataList();
      }
      //传感器
      else if(this.tabActive==2){
        this.getMeterDataList(true);
      }
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type,paramValue,callback) {
      let params = {
        'code': type ,
        "customerId":this.$util.cookies.get('customer_id')
      }
      if(paramValue){
        Object.assign(params,{...paramValue});
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },
    // 获取数据列表
    getCollectDataList () {
      this.dataListLoading = true
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecscollectequi/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.collectPage.page,
          'limit': this.collectPage.size,
          'key': this.dataForm.key,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.collectTableDataList = data.page.list
          this.collectPage.total = data.page.totalCount
        } else {
          this.collectTableDataList = []
          this.totalPage.total = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeCollectChangeHandle (val) {
      this.collectPage.size = val
      this.collectPage.page = 1
      this.getCollectDataList()
    },
    // 当前页
    currentCollectChangeHandle (val) {
      this.collectPage.page = val
      this.getCollectDataList()
    },

    getMeterDataList (flag) {
      if(flag){
        this.meterPage.page = 1
      }

      this.dataListLoading = true
      this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecsmeterinfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.meterPage.page,
            'limit': this.meterPage.size,
            'meterType': this.dataForm.energyType,
            'deviceName':this.dataForm.meterName,
            'status':this.dataForm.status?'0':'',
            "customerId":this.$util.cookies.get('customer_id'),
            'projectid':this.$util.cookies.get("cuuren_projectId"),
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.meterTableDataList = data.page.list
            this.meterPage.total = data.page.totalCount
          } else {
            this.meterTableDataList = []
            this.meterPage.total = 0
          }
          this.dataListLoading = false;
          //定时取数据
          this.timeOut = setTimeout(() => {this.getMeterDataList(false)}, this.meterAlarmRange);
        })
      },
    sizeMeterChangeHandle (val) {
      this.meterPage.size = val
      this.meterPage.page = 1
      this.getMeterDataList()
    },
    // 当前页
    currentMeterChangeHandle (val) {
      this.meterPage.page = val
      this.getMeterDataList()
    },
    exportExcel(){
      let header=['序号','区域名称','分类','设备名称','参数','时间',`用量(${this.unit})`]
      let props=['index','buildingName','meterType','deviceName','paramName','dateTime','value']
      let fileName=`用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      this.export2Excel(header,props,fileName,this.meterTableDataList)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  },
  destroyed(){
    if(this.timeOut){
      clearTimeout(this.timeOut);
    }
  }
  // watch:{
  //   'dataForm.status':function(newValue,oldValue){
  //      this.meterTableDataList.filter(ele=>{
  //        if(this.dataForm.status==1){
  //          return (new Date()).getTime()- new Date(scope.row.meterLastupdate).getTime()<this.meterAlarmRange;
  //        }
  //        else{
  //          return (new Date()).getTime()- new Date(scope.row.meterLastupdate).getTime()>this.meterAlarmRange;
  //        }
  //      })
  //   }
  // }
};
</script>

<style scoped>
  .search{
    margin-bottom: 15px;
  }
  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label{
    line-height: 27px;;
  }
  .device {
    display: inline-block;
    padding: 0 20px;
    line-height: 30px;
    color: #8a8c8e;
    /* border: 1px solid #d9ecff; */
    border-radius: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .actived {
    border: 1px solid #678af4;
    color: #678af4;
  }
  .show-device {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 30px;
    cursor: pointer;
    padding-right: 20px;
  }
  .tree-area { background-color: rgba(0, 0, 0, 0.1);
    width: 200px !important;
    /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
    padding-top: 10px;
  }
  .bg-white {
    box-shadow: 0px 0px 2px 2px #f7f6f6;
  }
  .el-tree-node__content {
    height: 30px !important;
  }
  .busi-chart{
      width: 100%;
      height: 400px;
      margin-top: 10x;
  }
  .objectTree {
      margin-left: 89px;
      position: absolute;
      overflow: auto;
      z-index: 100;
      height: 200px;
      /* border: 1px solid #ddd; */
      line-height: normal;
      z-index: 204;
      box-shadow: 0px 0px 1px 1px #e2dfdf;
      margin-top: 3px;
      border-radius: 4px;
    background-color: white;
  }
  .w-160{
    width: 160px
  }
</style>
